/*
 * UINuevoProducto.java
 *
 * Created on 28 de enero de 2008, 10:22
 */

package vista;

import Datos.Baja;
import Datos.Modificacion;
import controlador.CAlta;
import controlador.CListar;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import negocios.Configuracion;
import negocios.Producto;
import reportes.cExport_thread;

/**
 *
 * @author  marcelo gonzalez
 */
public class UINuevoProducto extends javax.swing.JFrame
{
    private Collection productos = new ArrayList();
    private boolean guardar = false;
    private Configuracion conf = new Configuracion();
    
    /** Creates new form UINuevoProducto */
    

    public UINuevoProducto()
    {
        initComponents();
        Dimension pantalla, cuadro;
	pantalla = Toolkit.getDefaultToolkit().getScreenSize();
	cuadro = this.getSize();
	this.setLocation(((pantalla.width - cuadro.width)/2), (pantalla.height - cuadro.height)/2);
        this.llenarTabla(new Producto());
        this.ajustarColumnas();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLLocalidad = new javax.swing.JLabel();
        jTNombreProducto = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jTCodigo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTNombreProducto1 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTPrecio = new javax.swing.JTextField();
        jCheckCuota = new javax.swing.JCheckBox();
        jBGuardar = new javax.swing.JButton();
        jBNuevo = new javax.swing.JButton();
        jBModificar = new javax.swing.JButton();
        jBSalir = new javax.swing.JButton();
        jBEliminar = new javax.swing.JButton();
        jBImprimir = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Administrar Productos");
        setResizable(false);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        jLLocalidad.setBackground(new java.awt.Color(255, 255, 204));
        jLLocalidad.setText("Filtrar por Nombre:");
        jLLocalidad.setOpaque(true);
        jLLocalidad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jLLocalidadKeyPressed(evt);
            }
        });

        jTNombreProducto.setToolTipText("ingrese letras para realizar un filtrado de productos en el listado.");
        jTNombreProducto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTNombreProductoKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTNombreProductoKeyReleased(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Nombre", "Precio"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setToolTipText("Elija un elemento del listado para modificarlo o eliminarlo.");
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos"));

        jTCodigo.setToolTipText("Ingrese un codigo numerico valido. Ej: 102");
        jTCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTCodigoKeyPressed(evt);
            }
        });

        jLabel3.setBackground(new java.awt.Color(255, 255, 204));
        jLabel3.setText("Codigo");
        jLabel3.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(255, 255, 102), null));
        jLabel3.setOpaque(true);

        jLabel4.setBackground(new java.awt.Color(255, 255, 204));
        jLabel4.setText("Nombre");
        jLabel4.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(255, 255, 102), null));
        jLabel4.setOpaque(true);

        jTNombreProducto1.setToolTipText("ingrese un nombre de producto valido.");
        jTNombreProducto1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTNombreProducto1ActionPerformed(evt);
            }
        });
        jTNombreProducto1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTNombreProducto1KeyPressed(evt);
            }
        });

        jLabel5.setBackground(new java.awt.Color(255, 255, 204));
        jLabel5.setText("Precio");
        jLabel5.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(255, 255, 102), null));
        jLabel5.setOpaque(true);

        jTPrecio.setText("0.00");
        jTPrecio.setToolTipText("Ingrese un preciovalido, solo digitos de 0-9 y el punto decimal. Ej: 12.00");
        jTPrecio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTPrecioActionPerformed(evt);
            }
        });
        jTPrecio.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTPrecioFocusLost(evt);
            }
        });
        jTPrecio.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTPrecioKeyPressed(evt);
            }
        });

        jCheckCuota.setText("Aplicable a Cuota");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTNombreProducto1, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jCheckCuota, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTNombreProducto1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCheckCuota))
                .addContainerGap())
        );

        jBGuardar.setText("Guardar");
        jBGuardar.setEnabled(false);
        jBGuardar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jBGuardarMouseClicked(evt);
            }
        });
        jBGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBGuardarActionPerformed(evt);
            }
        });

        jBNuevo.setText("Nuevo");
        jBNuevo.setToolTipText("Presione nuevo si desea agregar un nuevo producto.");
        jBNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBNuevoActionPerformed(evt);
            }
        });
        jBNuevo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jBNuevoKeyPressed(evt);
            }
        });

        jBModificar.setText("Modificar");
        jBModificar.setToolTipText("Permite guargar los cambios realizados al registro seleccionado.");
        jBModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBModificarActionPerformed(evt);
            }
        });
        jBModificar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jBModificarKeyPressed(evt);
            }
        });

        jBSalir.setText("Salir");
        jBSalir.setToolTipText("Cierra la ventana  actual y vuelve al menu principal.");
        jBSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSalirActionPerformed(evt);
            }
        });

        jBEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/pllena.gif"))); // NOI18N
        jBEliminar.setToolTipText("eliminar un registro seleccionado del listado.");
        jBEliminar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jBEliminarMouseClicked(evt);
            }
        });
        jBEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBEliminarActionPerformed(evt);
            }
        });
        jBEliminar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jBEliminarKeyPressed(evt);
            }
        });

        jBImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/printer.gif"))); // NOI18N
        jBImprimir.setToolTipText("imprimir un reporte del listado completo de productos.");
        jBImprimir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jBImprimirMouseClicked(evt);
            }
        });
        jBImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBImprimirActionPerformed(evt);
            }
        });
        jBImprimir.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jBImprimirKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLLocalidad, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jTNombreProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
                                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jBEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jBImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jBGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLLocalidad, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTNombreProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jBEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jBImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBModificar)
                    .addComponent(jBNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBGuardarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jBGuardarActionPerformed
    {//GEN-HEADEREND:event_jBGuardarActionPerformed
// TODO add your handling code here:
         switch (this.controlar()){
            case 0: this.guardar(); break;
            case 1: JOptionPane.showMessageDialog(null,"Debe ingresar todos los datos solicitados","Faltan Datos",JOptionPane.ERROR_MESSAGE);break;
         }
    }//GEN-LAST:event_jBGuardarActionPerformed

    private void jTPrecioKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTPrecioKeyPressed
    {//GEN-HEADEREND:event_jTPrecioKeyPressed
// TODO add your handling code here:
        char c = evt.getKeyChar();
        if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) ||(c == KeyEvent.VK_ENTER) ||(c == KeyEvent.VK_DELETE)  ||(c == KeyEvent.VK_ESCAPE) || (c == '.'))))
        {    
            getToolkit().beep();
            JOptionPane.showMessageDialog(null,"Debe introducir un precio valido ej: 12.00","Atencion",JOptionPane.ERROR_MESSAGE);
            this.jTPrecio.setText("");
            this.jTPrecio.requestFocus();
            evt.consume();
        }
        if(evt.getKeyCode()==27)
            this.dispose();
    }//GEN-LAST:event_jTPrecioKeyPressed

    private void jTPrecioActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jTPrecioActionPerformed
    {//GEN-HEADEREND:event_jTPrecioActionPerformed
// TODO add your handling code here:
    }//GEN-LAST:event_jTPrecioActionPerformed

    private void jBSalirActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jBSalirActionPerformed
    {//GEN-HEADEREND:event_jBSalirActionPerformed
// TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jBSalirActionPerformed

    private void jBModificarKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jBModificarKeyPressed
    {//GEN-HEADEREND:event_jBModificarKeyPressed
// TODO add your handling code here:
    }//GEN-LAST:event_jBModificarKeyPressed

    private void jBModificarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jBModificarActionPerformed
    {//GEN-HEADEREND:event_jBModificarActionPerformed
// TODO add your handling code here:
        
        switch (this.controlar()){
            case 0: this.modificar(); break;
            case 1: JOptionPane.showMessageDialog(null,"Debe ingresar todos los datos solicitados","Faltan Datos",JOptionPane.ERROR_MESSAGE);break;
        }
//        if((this.controlar()==0) && (this.jTCodigo.getText().trim().length() != 0))
//            this.modificar();
//        else
//            JOptionPane.showMessageDialog(null,"Debe ingresar los datos completos","Faltan Datos o estan incorrectos",JOptionPane.ERROR_MESSAGE);
    }//GEN-LAST:event_jBModificarActionPerformed

    private void jBNuevoKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jBNuevoKeyPressed
    {//GEN-HEADEREND:event_jBNuevoKeyPressed
// TODO add your handling code here:
        if(evt.getKeyCode()==27)
            this.dispose();
        if(evt.getKeyCode()==10)
        {
            this.guardar = true;
            this.jBGuardar.setEnabled(true);
            this.jTCodigo.setText("");
            this.jTNombreProducto1.setText("");
            this.jTPrecio.setText("");
            this.jTNombreProducto1.requestFocus();
        }
    }//GEN-LAST:event_jBNuevoKeyPressed

    private void jBNuevoActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jBNuevoActionPerformed
    {//GEN-HEADEREND:event_jBNuevoActionPerformed
// TODO add your handling code here:
        this.guardar = true;
        this.jBGuardar.setEnabled(true);
        this.jTCodigo.setText("");
        this.jTNombreProducto1.setText("");
        this.jTPrecio.setText("");
        this.jTCodigo.requestFocus();
    }//GEN-LAST:event_jBNuevoActionPerformed

    private void jTNombreProducto1KeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTNombreProducto1KeyPressed
    {//GEN-HEADEREND:event_jTNombreProducto1KeyPressed
// TODO add your handling code here:
        if(evt.getKeyCode()==27)
            this.dispose();
        if(evt.getKeyChar()==10)
            this.jTPrecio.requestFocus();


    }//GEN-LAST:event_jTNombreProducto1KeyPressed

    private void jTNombreProducto1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jTNombreProducto1ActionPerformed
    {//GEN-HEADEREND:event_jTNombreProducto1ActionPerformed
// TODO add your handling code here:
    }//GEN-LAST:event_jTNombreProducto1ActionPerformed

    private void jTCodigoKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTCodigoKeyPressed
    {//GEN-HEADEREND:event_jTCodigoKeyPressed
// TODO add your handling code here:
        
        char c = evt.getKeyChar();
        if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) ||(c == KeyEvent.VK_ENTER) ||(c == KeyEvent.VK_DELETE)  ||(c == KeyEvent.VK_ESCAPE))))
        {    
            getToolkit().beep();
            JOptionPane.showMessageDialog(null,"Debe introducir un valor valido ej: 12","Atencion",JOptionPane.ERROR_MESSAGE);
            this.jTCodigo.setText("");
            this.jTCodigo.requestFocus();
            evt.consume();
        }
        if(evt.getKeyCode()==27)
            this.dispose();
        if(evt.getKeyChar()==10)
            this.jTNombreProducto1.requestFocus();
        
    }//GEN-LAST:event_jTCodigoKeyPressed

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTable1KeyPressed
    {//GEN-HEADEREND:event_jTable1KeyPressed
// TODO add your handling code here:
        if(evt.getKeyCode()==27)
            this.dispose();
        if(evt.getKeyCode()==127)
            this.borrarRegistro(this.jTable1.getSelectedRow());
    }//GEN-LAST:event_jTable1KeyPressed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jTable1MouseClicked
    {//GEN-HEADEREND:event_jTable1MouseClicked
// cuando se seleccione una fila, los datos de esa fila deben aparecer en los textbox de abajo solo si no se esta por cargar un nuevo elemento
        if(!this.guardar)
        {
            Iterator it = productos.iterator();
            Producto p = new Producto();
            while(it.hasNext())
            {
                p = (Producto)it.next();
                if(p.getIdproducto() == Integer.parseInt(String.valueOf(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0))))
                {
                    this.jTCodigo.setText(String.valueOf(p.getIdproducto()).trim());
                    this.jTNombreProducto1.setText(p.getDenominacion().trim());
                    this.jTPrecio.setText(String.valueOf(p.getPrecio()).trim());
                    if(p.getIdproducto() == Integer.parseInt(String.valueOf(this.conf.getIdproducto())))
                        this.jCheckCuota.setSelected(true);
                    else
                        this.jCheckCuota.setSelected(false);
                }
            }
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jTNombreProductoKeyReleased(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTNombreProductoKeyReleased
    {//GEN-HEADEREND:event_jTNombreProductoKeyReleased
// TODO add your handling code here:
        this.filtrar(this.jTNombreProducto.getText().toUpperCase());
    }//GEN-LAST:event_jTNombreProductoKeyReleased

    private void jTNombreProductoKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTNombreProductoKeyPressed
    {//GEN-HEADEREND:event_jTNombreProductoKeyPressed
// TODO add your handling code here:
        if(evt.getKeyCode()==27)
            this.dispose();
    }//GEN-LAST:event_jTNombreProductoKeyPressed

    private void jLLocalidadKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jLLocalidadKeyPressed
    {//GEN-HEADEREND:event_jLLocalidadKeyPressed
// TODO add your handling code here:
        if(evt.getKeyCode()==27)
            this.dispose();
    }//GEN-LAST:event_jLLocalidadKeyPressed

    private void jBEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBEliminarActionPerformed
        // TODO add your handling code here:
      
}//GEN-LAST:event_jBEliminarActionPerformed

    private void jBEliminarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jBEliminarKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==27)
            this.dispose();
        this.borrarRegistro(jTable1.getSelectedRow());
}//GEN-LAST:event_jBEliminarKeyPressed

    private void jBEliminarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBEliminarMouseClicked
        // TODO add your handling code here:
        this.borrarRegistro(jTable1.getSelectedRow());
    }//GEN-LAST:event_jBEliminarMouseClicked

    private void jTPrecioFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTPrecioFocusLost
        // TODO add your handling code here:
        
//        int posicion= this.jTPrecio.getText().trim().indexOf(",");
//        if (posicion>-1){
//            JOptionPane.showMessageDialog(this, "Hay una coma, reemplaze por punto decimal...","Atencion:", JOptionPane.INFORMATION_MESSAGE);
//            this.jTPrecio.requestFocus();
//        }
        
        
    }//GEN-LAST:event_jTPrecioFocusLost

    private void jBGuardarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBGuardarMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jBGuardarMouseClicked

    private void jBImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBImprimirActionPerformed
        // TODO add your handling code here:
       
}//GEN-LAST:event_jBImprimirActionPerformed

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==27)
            this.dispose();
    }//GEN-LAST:event_formKeyPressed

    private void jBImprimirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBImprimirMouseClicked
        // TODO add your handling code here:
            cExport_thread report = new cExport_thread(15);
            report.start();
        
    }//GEN-LAST:event_jBImprimirMouseClicked

    private void jBImprimirKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jBImprimirKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==10){
            cExport_thread report = new cExport_thread(15);
            report.start();
        }
    }//GEN-LAST:event_jBImprimirKeyPressed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new UINuevoProducto().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBEliminar;
    private javax.swing.JButton jBGuardar;
    private javax.swing.JButton jBImprimir;
    private javax.swing.JButton jBModificar;
    private javax.swing.JButton jBNuevo;
    private javax.swing.JButton jBSalir;
    private javax.swing.JCheckBox jCheckCuota;
    private javax.swing.JLabel jLLocalidad;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTCodigo;
    private javax.swing.JTextField jTNombreProducto;
    private javax.swing.JTextField jTNombreProducto1;
    private javax.swing.JTextField jTPrecio;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
    
    
    private void llenarTabla(Producto p)
    {
        //De alguna forma obtengo una coleccion con los barrios cargados en la base de datos
        CListar listar = new CListar();
        productos = listar.hacerListado(p);
        this.conf = listar.hacerListado(conf);
        listar = null;
        Iterator it = productos.iterator();
        // ahora obtengo el modelo de la tabla
        DefaultTableModel modelo = (DefaultTableModel)this.jTable1.getModel();
        String datos[] = new String[3];
        while(it.hasNext())
        {
            p = (Producto)it.next();
            datos[0] = String.valueOf(p.getIdproducto()).trim();
            datos[1] = p.getDenominacion().trim();
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            datos[2] = nf.format(p.getPrecio()).trim(); // convertir a formato de moneda para mostrar
            modelo.addRow(datos);
        }
    }
    
    private int controlar()
    {
        int control = 0;
        if(this.jTNombreProducto1.getText().trim().length()==0)
            control = 1;
        if(this.jTPrecio.getText().trim().length()==0)
            control = 1;
        if(this.jTCodigo.getText().trim().length() == 0)
            control = 1;
        return control;
    }
    
    private void guardar()
    {
        //Iterator it = productos.iterator();
        Producto producto = new Producto();
        producto.setExiste("S");
        producto.setDenominacion(this.jTNombreProducto1.getText().toUpperCase().trim());
        producto.setPrecio(Double.parseDouble(this.jTPrecio.getText().trim()));
        producto.setIdproducto(Integer.parseInt(this.jTCodigo.getText()));
        this.guardar = false;
        this.jBGuardar.setEnabled(false);
        // aqui va el codigo que guarda en la base de datos
        CAlta alta = new CAlta();
        int respuesta = alta.hacerAlta(producto);
        if(respuesta != 0)
                JOptionPane.showMessageDialog(null,"Error en la carga de datos, verifique que el codigo no pertenezca a otro producto","Error",JOptionPane.ERROR_MESSAGE);
        else
            if(this.jCheckCuota.isSelected())
            {
                this.conf.setIdproducto(Integer.parseInt(this.jTCodigo.getText()));
                if(alta.hacerAlta(this.conf) == 0)
                    JOptionPane.showMessageDialog(null,"Los datos se cargaron correctamente","Carga Finalizada",JOptionPane.INFORMATION_MESSAGE);
                else
                    JOptionPane.showMessageDialog(null,"Error en la carga de datos, verifique que el codigo no pertenezca a otro producto","Error",JOptionPane.ERROR_MESSAGE);
            }
            else
                JOptionPane.showMessageDialog(null,"Los datos se cargaron correctamente","Carga Finalizada",JOptionPane.INFORMATION_MESSAGE);
                
        this.limpiar();
        this.llenarTabla(new Producto());
        this.limpiarCampos();
    }
    
    
    private void modificar()
    {
//        Iterator it = productos.iterator();
        Producto producto = new Producto();
        producto.setExiste("S");
        producto.setDenominacion(this.jTNombreProducto1.getText().toUpperCase().trim());
        producto.setPrecio(Double.parseDouble(this.jTPrecio.getText().trim()));
        producto.setIdproducto(Integer.parseInt(this.jTCodigo.getText()));
        this.guardar = false;
        this.jBGuardar.setEnabled(false);
        // aqui va el codigo que guarda en la base de datos
        Modificacion mod = new Modificacion();
        int respuesta = mod.modificar(producto);
        if(respuesta == 0)
                JOptionPane.showMessageDialog(null,"Error en la carga de datos, verifique el codigo de producto","Error",JOptionPane.ERROR_MESSAGE);
        else
            if(this.jCheckCuota.isSelected())
            {
                this.conf.setIdproducto(Integer.parseInt(this.jTCodigo.getText()));
                if(mod.modificar(this.conf) != 0)
                    JOptionPane.showMessageDialog(null,"Los datos se modificaron correctamente","Carga Finalizada",JOptionPane.INFORMATION_MESSAGE);
                else
                    JOptionPane.showMessageDialog(null,"Error en la carga de datos, verifique que el codigo no pertenezca a otro producto","Error",JOptionPane.ERROR_MESSAGE);
            }
            else
                JOptionPane.showMessageDialog(null,"Los datos se modificaron correctamente","Carga Finalizada",JOptionPane.INFORMATION_MESSAGE);
                
        this.limpiar();
        this.llenarTabla(new Producto());
        this.limpiarCampos();
    }
    
    private void limpiar()
    {
        DefaultTableModel modelo = (DefaultTableModel)this.jTable1.getModel();
        while(this.jTable1.getRowCount() != 0)
                modelo.removeRow(0);
        modelo = null;
    }
    
    private void borrarRegistro(int fila)
    {
        Iterator it = productos.iterator();
        while(it.hasNext())
        {
            Producto p = (Producto)it.next();
            if(p.getIdproducto() == Integer.parseInt(String.valueOf(this.jTable1.getValueAt(fila,0))))
            {
                Baja baja = new Baja();
                int respuesta = baja.eliminar(p);
                baja = null;
                if(respuesta == 0)
                    JOptionPane.showMessageDialog(null,"Error al dar de baja la localidad","Error",JOptionPane.ERROR_MESSAGE);
                else
                    JOptionPane.showMessageDialog(null,"El Producto se elimino correctamente","Baja Completada",JOptionPane.INFORMATION_MESSAGE);
            }
            p = null;
        }
        it = null;
        this.limpiar();
        this.llenarTabla(new Producto());
        this.limpiarCampos();
    }
    
    private void filtrar(String cadena)
    {
        // de alguna forma mando la cadena para que otro objeto me devuelva una nueva coleccion con los barrios filtrados
        //barrios = algo(cadena);
        // solo queda limpiar la tabla y volverla a cargar
        this.limpiar();
        Producto p = new Producto();
        p.setDenominacion(cadena);
        this.llenarTabla(p);
    }
    
     private void limpiarCampos()
     {
        this.jTCodigo.setText("");
        this.jTNombreProducto1.setText("");
        this.jTPrecio.setText("");
     }
     
     private void ajustarColumnas()
     {
         TableColumn column = null;
         for (int i = 0; i < 2; i++) 
        {
            column = jTable1.getColumnModel().getColumn(i);
            switch(i)
            {
                case 0:
                        column.setPreferredWidth(15);
                        break;
                case 1:
                        column.setPreferredWidth(223);
                        break;
            }
        }
     }
}
